package ecoll.server.quiz;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

@SuppressWarnings("serial")
public class QuizTaskServlet extends HttpServlet {

	public static void schedule(String roomName, String roomRoundId, int delay,
			boolean answered) {
		Queue queue = QueueFactory.getDefaultQueue();
		String taskName = roomRoundId;
		if (answered) {
			if (!queue.deleteTask(roomRoundId))
				return;
			taskName += "A";
		}
		queue.add(TaskOptions.Builder.withUrl("/ecoll/task").taskName(taskName)
				.countdownMillis(delay * 1000).param("quizRoom", roomName)
				.param("roundId", roomRoundId).method(Method.GET));

	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) {
		String roomName = (String) request.getParameter("quizRoom");
		String roundId = (String) request.getParameter("roundId");
		QuizRoom room = QuizDatabase.getRoom(roomName);
		if (room != null && room.getRoundId().equals(roundId))
			room.newQuestion();
	}
}
